<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          @click="handleAdd"
          v-hasPermi="['api:category:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['api:category:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['api:category:remove']"
          >删除</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['api:category:export']"
          >导出</el-button
        >
      </el-col> -->
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="expressList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="模板编号"
        align="center"
        prop="id"
        min-width="100"
        show-overflow-tooltip
      />
      <el-table-column
        label="模板名称"
        align="center"
        prop="name"
        min-width="160"
        show-overflow-tooltip
      />
      <el-table-column label="计费方式" align="center" prop="chargeMode">
        <template slot-scope="scope">
          <!-- {{
            scope.row.chargeMode == "1"
              ? "按件"
              : scope.row.chargeMode == "2"
              ? "按重量"
              : scope.row.chargeMode == "3"
              ? "按体积"
              : ""
          }} -->
          <dict-tag
            :options="dict.type.charge_mode"
            :value="scope.row.status"
          />
        </template>
      </el-table-column>
      <el-table-column label="是否启用" align="center" prop="status">
        <template slot-scope="scope">
          <!-- {{
            scope.row.status == "0" ? "否" : scope.row.status == "1" ? "是" : ""
          }} -->
          <!-- <el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(scope.row)"
          >
          </el-switch> -->
          <dict-tag :options="dict.type.yes_no" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        min-width="160"
        sortable
      />
      <el-table-column
        label="更新时间"
        align="center"
        prop="updateTime"
        min-width="160"
        sortable
      />
      <el-table-column label="排序" align="center" prop="sort" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        fixed="right"
        min-width="140"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['api:category:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['api:category:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改产品分类对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="950px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="模板名称" prop="name">
          <el-input placeholder="请输入模板名称" v-model="form.name" />
        </el-form-item>
        <el-form-item label="计费方式" prop="chargeMode">
          <el-radio-group v-model="form.chargeMode">
            <el-radio
              v-for="dict in dict.type.charge_mode"
              :key="dict.value"
              :label="parseInt(dict.value)"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="配送区域及运费" prop="expressTemplateChargeList">
          <el-table :data="form.expressTemplateChargeList">
            <el-table-column label="可配送区域" min-width="160">
              <template slot-scope="scope">
                <div
                  class="show-send-area"
                  style="display: flex; align-items: center"
                >
                  <div class="show-send-area-txt">{{ scope.row.scope }}</div>
                  <div
                    style="cursor: pointer; width: 20px; height: 20px"
                    class="ml10"
                    @click="toEidtSendArea(scope.row, scope.$index)"
                  >
                    <i class="el-icon-edit"></i>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              label="首件(个)"
              align="center"
              prop="roleType"
              min-width="100"
            >
              <template slot-scope="scope">
                <el-input
                  placeholder="请输入"
                  v-model.trim="scope.row.startCount"
                />
              </template>
            </el-table-column>
            <el-table-column
              label="起步价(元)"
              align="center"
              prop="roleType"
              min-width="100"
            >
              <template slot-scope="scope">
                <el-input
                  placeholder="请输入"
                  v-model.trim="scope.row.startPrice"
                />
              </template>
            </el-table-column>
            <el-table-column
              label="续件(个)"
              align="center"
              prop="roleType"
              min-width="100"
            >
              <template slot-scope="scope">
                <el-input
                  placeholder="请输入"
                  v-model.trim="scope.row.extraCount"
                />
              </template>
            </el-table-column>
            <el-table-column
              label="续价价(元)"
              align="center"
              prop="roleType"
              min-width="100"
            >
              <template slot-scope="scope">
                <el-input
                  placeholder="请输入"
                  v-model.trim="scope.row.extraPrice"
                />
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              align="center"
              class-name="small-padding fixed-width"
            >
              <template slot-scope="scope">
                <el-button
                  type="danger"
                  size="small"
                  @click="toDeleteExpressInfo(scope)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <el-button
            type="primary"
            plain
            icon="Plus"
            class="mt10"
            @click="toShowSendArea"
            >指定可配送区域</el-button
          >
        </el-form-item>

        <el-form-item label=" " prop="status">
          <el-checkbox v-model="isStatus" label="是否启用" />
        </el-form-item>
      </el-form>
      <div
        slot="footer"
        class="dialog-footer"
        style="display: flex; justify-content: flex-end"
      >
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="选择配送区域"
      :visible.sync="openSendArea"
      width="800px"
      append-to-body
    >
      <el-checkbox-group v-model="selectArea">
        <el-checkbox
          :label="item.name"
          v-for="item in sendAreaList"
          :key="item.id"
          class="mb10"
        >
          {{ item.name }}
        </el-checkbox>
        <!-- <el-checkbox label="Option A">
          <el-popover :width="500" trigger="hover">
            <template #reference>
              <div style="display: flex; align-items: center">
                北京
                <el-icon size="12" color="#999" class="ml10"
                  ><i class="el-icon-arrow-down"></i>
                /></el-icon>
              </div>
            </template>
            <template slot-scope>
              <el-checkbox-group style="display: flex; flex-wrap: wrap">
                <el-checkbox label="城市1213323223" />
                <el-checkbox label="城市qweqeweewe" />
                <el-checkbox label="城市asdadadddd" />
                <el-checkbox label="城市zxcxcxczxc" />
                <el-checkbox label="城市1213323223" />
                <el-checkbox label="城市qweqeweewe" />
                <el-checkbox label="城市asdadadddd" />
                <el-checkbox label="城市zxcxcxczxc" />
              </el-checkbox-group>
            </template>
          </el-popover>
        </el-checkbox> -->
      </el-checkbox-group>

      <div
        slot="footer"
        class="dialog-footer"
        style="display: flex; justify-content: flex-end"
      >
        <el-button type="primary" @click="submitSendArea">确 定</el-button>
        <el-button @click="cancelSendArea">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listTemplate,
  getTemplate,
  addTemplate,
  updateTemplate,
  delTemplate,
  getProvince,
} from "@/api/djk/platformMgr/expressSet";

export default {
  name: "Category",
  dicts: ["charge_mode", "yes_no"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      expressList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      // 表单参数
      form: {
        expressTemplateChargeList: [],
        status: 0,
      },
      isStatus: false,
      //运费明细
      // 表单校验
      rules: {
        name: [
          { required: true, message: "模板名称不能为空", trigger: "blur" },
        ],
        chargeMode: [
          { required: true, message: "请选择计费方式", trigger: "change" },
        ],
        expressTemplateChargeList: [
          {
            type: "array",
            required: true,
            message: "请选择配送区域及运费",
            trigger: "change",
          },
        ],
      },
      // 配送区域
      sendAreaList: [],
      openSendArea: false,
      selectIdx: null,
      selectArea: [],
    };
  },
  created() {
    this.getList();
    this.getProvinceInfo();
  },
  methods: {
    // 获取省份信息
    getProvinceInfo() {
      getProvince().then((res) => {
        this.sendAreaList = res.data;
      });
    },
    /** 查询产品分类列表 */
    getList() {
      this.loading = true;
      listTemplate(this.queryParams).then((response) => {
        this.expressList = response.data;
        this.total = response.data.length;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        chargeMode: null,
        status: null,
        expressTemplateChargeList: [],
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增运费模板";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getTemplate(id).then((response) => {
        this.isStatus = response.data.status == 1 ? true : false;
        this.form = response.data;
        this.open = true;
        this.title = "修改运费模板";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.status = this.isStatus ? 1 : 0;

          if (this.form.id != null) {
            updateTemplate(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTemplate(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除模板编号为"' + ids + '"的数据项？')
        .then(function () {
          return delTemplate(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    // 是否启用
    handleStatusChange(row) {
      let text = row.status === 0 ? "确认禁用？" : "确认启用？";
      this.$confirm(text, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // changeDataStatus({
          //   bodyId: row.bodyId,
          //   dataStatus: row.dataStatus,
          // }).then((response) => {
          //   this.msgSuccess(response.msg);
          //   this.getList();
          // });
        })
        .catch(() => {
          row.status = row.status === 0 ? 1 : 0;
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      // this.download(
      //   "api/category/export",
      //   {
      //     ...this.queryParams,
      //   },
      //   `category_${new Date().getTime()}.xlsx`
      // );
    },
    // 可配送
    toShowSendArea() {
      this.selectIdx = this.form.expressTemplateChargeList.length;
      this.selectArea = [];
      this.openSendArea = true;
    },
    toEidtSendArea(row, index) {
      this.selectIdx = index;
      this.selectArea = row.scope.split(",");
      this.openSendArea = true;
    },
    toDeleteExpressInfo({ $index }) {
      this.form.expressTemplateChargeList.splice($index, 1);
    },
    submitSendArea() {
      this.openSendArea = false;
      let item = this.form.expressTemplateChargeList[this.selectIdx];
      if (item) {
        item.scope = this.selectArea.join(",");
      } else {
        this.form.expressTemplateChargeList.push({
          scope: this.selectArea.join(","),
          startCount: 0,
          startPrice: 0,
          extraCount: 0,
          extraPrice: 0,
        });
        // item.scope = this.selectArea.join(",");
        // item.startCount = 0;
        // item.startPrice = 0;
        // item.extraCount = 0;
        // item.extraPrice = 0;
      }
    },
    cancelSendArea() {
      this.openSendArea = false;
    },
  },
};
</script>
